package com.yuanduo_app.window;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;

import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.xujl.fastlib.base.BaseRvAdapter;

import com.yuanduo_app.R;
import com.yuanduo_app.entity.NearbyOilLevelEntity;
import com.yuanduo_app.utils.ViewHelper;

import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class NearbyOilBottomWindow extends BaseWindow {
    private RecyclerView rv;
    private Callback mCallback;

    public NearbyOilBottomWindow (Context context, Callback callback) {
        super(context);
        mCallback = callback;
        setPopupGravity(Gravity.BOTTOM);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        setWidth(dm.widthPixels);
        setHeight((int) (dm.heightPixels * 0.4f));
    }

//    @Override
//    protected Animation onCreateShowAnimation () {
//        return getTranslateVerticalAnimation(getHeight(), 0, 1000);
//    }
//
//    @Override
//    protected Animation onCreateDismissAnimation () {
//        return getTranslateVerticalAnimation(0, getHeight(), 1000);
//    }

    @Override
    public View onCreateContentView () {
        View view = createPopupById(R.layout.window_nearby_oil_bottom);
        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> dismiss());
        rv = view.findViewById(R.id.rv);
        ViewHelper.addItemHorizontalVerticalDecoration(rv, 10, R.color.transparent);
        rv.setLayoutManager(new GridLayoutManager(view.getContext(), 4));
        return view;
    }

    public void showPopupWindow (List<NearbyOilLevelEntity> list) {
        super.showPopupWindow();
        if (rv.getAdapter() != null) {
            rv.getAdapter().notifyDataSetChanged();
            return;
        }
        rv.setAdapter(new BaseRvAdapter<NearbyOilLevelEntity>(R.layout.item_window_nearby_oil_bottom, list) {
            @Override
            protected void convert (BaseViewHolder baseViewHolder, NearbyOilLevelEntity nearbyOilLevelEntity) {
                baseViewHolder.setText(R.id.tv, nearbyOilLevelEntity.getName());
                ((CheckBox) baseViewHolder.getView(R.id.tv)).setChecked(nearbyOilLevelEntity.isChecked());
            }
        });
        ((BaseRvAdapter) rv.getAdapter()).setOnItemClickListener((adapter, view, position) -> {
            final NearbyOilLevelEntity levelEntity = list.get(position);
            mCallback.onItemClick(levelEntity);
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setChecked(i == position);
            }
            adapter.notifyDataSetChanged();
            dismiss();
        });
    }


    public interface Callback {
        void onItemClick (NearbyOilLevelEntity entity);
    }
}
